package com.atguigu.gulimall.product.service.impl;

import com.atguigu.common.constant.ProductConstant;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;
import com.atguigu.gulimall.product.dao.AttrAttrgroupRelationDao;
import com.atguigu.gulimall.product.dao.AttrDao;
import com.atguigu.gulimall.product.dao.AttrGroupDao;
import com.atguigu.gulimall.product.dao.CategoryDao;
import com.atguigu.gulimall.product.entity.AttrAttrgroupRelationEntity;
import com.atguigu.gulimall.product.entity.AttrEntity;
import com.atguigu.gulimall.product.entity.AttrGroupEntity;
import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.AttrService;
import com.atguigu.gulimall.product.service.CategoryService;
import com.atguigu.gulimall.product.vo.AttrRespVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    @Resource
    private AttrAttrgroupRelationDao attrAttrgroupRelationDao;

    @Resource
    private AttrGroupDao attrGroupDao;
    @Resource
    private CategoryDao categoryDao;

    @Resource
    private CategoryService categoryService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    @Transactional
    public void saveAttr(AttrEntity attr) {
        // 保存基本数据
        this.save(attr);
        // 保存关联关系
        if (attr.getType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode() && attr.getGroupId() != null) {
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
            attrAttrgroupRelationEntity.setAttrId(attr.getId());
            attrAttrgroupRelationEntity.setAttrGroupId(attr.getGroupId());
            attrAttrgroupRelationDao.insert(attrAttrgroupRelationEntity);
        }
    }

    @Override
    public PageUtils queryBaseAttrPage(Map<String, Object> params, Long categoryId, String type) {
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("type", "base".equalsIgnoreCase(type) ? ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode() : ProductConstant.AttrEnum.ATTR_TYPE_SALE.getCode());
        // 条件过滤
        if (categoryId != 0) {
            wrapper.eq("category_id", categoryId);
        }
        // 关键字
        String key = (String) params.get("key");
        if (StringUtils.isNotEmpty(key)) {
            wrapper.and((obj) -> {
               obj.eq("id", key).or().like("name", key);
            });
        }
        // 查询
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                wrapper
        );
        PageUtils pageUtils = new PageUtils(page);
        // 封装数据
        List<AttrEntity> records = page.getRecords();
        List<AttrRespVo> list = records.stream().map((attrEntity) -> {
            AttrRespVo attrRespVo = new AttrRespVo();
            BeanUtils.copyProperties(attrEntity, attrRespVo);
            // 设置分类和分组名称
            AttrAttrgroupRelationEntity relationEntity = attrAttrgroupRelationDao.
                    selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrEntity.getId()));
            if (relationEntity != null && relationEntity.getAttrGroupId() != null) {
                AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(relationEntity.getAttrGroupId());
                attrRespVo.setGroupName(attrGroupEntity.getName());
            }

            CategoryEntity categoryEntity = categoryDao.selectById(attrEntity.getCategoryId());
            if (categoryEntity != null) {
                attrRespVo.setCatelogName(categoryEntity.getName());
            }
            return attrRespVo;
        }).collect(Collectors.toList());
        pageUtils.setList(list);
        return pageUtils;

    }

    @Override
    public AttrRespVo getAttrInfo(Long id) {
        AttrEntity attrEntity = this.getById(id);
        AttrRespVo result = new AttrRespVo();
        BeanUtils.copyProperties(attrEntity, result);
        // 设置所属分组和名称
        if (attrEntity.getType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()) {
            AttrAttrgroupRelationEntity attrgroupRelation = attrAttrgroupRelationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", id));
            if (attrgroupRelation != null) {
                result.setGroupId(attrgroupRelation.getAttrGroupId());
                AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(result.getGroupId());
                if (attrGroupEntity != null) {
                    result.setGroupName(attrGroupEntity.getName());
                }
            }
        }
        // 设置所属分类
        Long categoryId = attrEntity.getCategoryId();
        Long[] categoryIds = categoryService.findCategoryIds(categoryId);
        result.setCategoryIds(categoryIds);
        CategoryEntity categoryEntity = categoryDao.selectById(categoryId);
        if (categoryEntity != null) {
            result.setCatelogName(categoryEntity.getName());
        }
        return result;
    }

    @Override
    @Transactional
    public void updateAttr(AttrEntity attr) {
        this.updateById(attr);
        if (attr.getType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()) {
            // 修改关联表
            AttrAttrgroupRelationEntity attrgroupRelation = new AttrAttrgroupRelationEntity();
            attrgroupRelation.setAttrId(attr.getId());
            attrgroupRelation.setAttrGroupId(attr.getGroupId());

            Integer count = attrAttrgroupRelationDao.selectCount(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attr.getId()));
            if (count > 0) {
                // 修改
                attrAttrgroupRelationDao.update(attrgroupRelation, new UpdateWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attr.getId()));
            } else {
                // 新增
                attrAttrgroupRelationDao.insert(attrgroupRelation);
            }
        }
    }

    /**
     * 根据分组id查找所有的基本属性
     * @param attrGroupId
     * @return
     */
    @Override
    public List<AttrEntity> getRelationAttr(Long attrGroupId) {
        List<AttrAttrgroupRelationEntity> relationEntityList = attrAttrgroupRelationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_group_id", attrGroupId));
        if (!CollectionUtils.isEmpty(relationEntityList)) {
            List<Long> ids = relationEntityList.stream().map(b -> b.getAttrId()).collect(Collectors.toList());
            List<AttrEntity> attrEntities = this.listByIds(ids);
            return attrEntities;
        }
        return null;
    }

    /**
     * 批量移除关联
     * @param relationEntities
     */
    @Override
    @Transactional
    public void deleteRelation(List<AttrAttrgroupRelationEntity> relationEntities) {
        attrAttrgroupRelationDao.deleteRelation(relationEntities);
    }

    /**
     * 获取当前分组没有关联的所有属性
     * @param params
     * @param attrGroupId
     * @return
     */
    @Override
    public PageUtils getNoRelationAttr(Map<String, Object> params, Long attrGroupId) {
        // 当前分组只能关联的所属分类中的属性
        AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrGroupId);
        Long categoryId = attrGroupEntity.getCategoryId();
        // 当前分组只能关联别的分组没有引用的属性
        // 当前分类下的其他分组
        List<AttrGroupEntity> group = attrGroupDao.selectList(new QueryWrapper<AttrGroupEntity>().eq("category_id", categoryId));
        List<Long> groupIds = group.stream().map(b -> b.getId()).collect(Collectors.toList());
        // 这些分组关联的属性
        List<AttrAttrgroupRelationEntity> relationEntities = attrAttrgroupRelationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().in("attr_group_id", groupIds));
        List<Long> longList = relationEntities.stream().map(item -> item.getAttrId()).collect(Collectors.toList());
        // 从当前分类的所有属性中，移除这些属性，得到未关联的数据
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<AttrEntity>().eq("category_id", categoryId).eq("type", ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode());
        if (!CollectionUtils.isEmpty(longList)) {
            wrapper.notIn("id", longList);
        }
        String key = (String) params.get("key");
        if (StringUtils.isNotEmpty(key)) {
            wrapper.and((obj) -> {
                obj.eq("id", key).or().like("name", key);
            });
        }
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                wrapper
        );
        return new PageUtils(page);
    }

    /**
     * 在指定的所有属性id集合里面，挑出检索属性
     * @param attrIds
     * @return
     */
    @Override
    public List<Long> selectSearchAttrs(List<Long> attrIds) {
        return this.baseMapper.selectSearchAttrs(attrIds);
    }

}